package com.optitronics.controllers;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.optitronics.beans.Product;
import com.optitronics.ui.ComboBoxSupport;
import com.optitronics.util.OptitronicsConstants;
import com.optitronics.util.OptitronicsUtils;

@RequestMapping("/products")
@Controller
public class ProductController {

	@Autowired
	private MessageSource messageSource;

	@Autowired
	private GenericConversionService conversionService;

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String show(@PathVariable("id") Integer id, Model model) {
		Product product = Product.findProduct(id);

		model.addAttribute("product", product);
		model.addAttribute("itemId", id);
		model.addAttribute("update", OptitronicsUtils.isUserAdmin());
		boolean addToCart = OptitronicsUtils.isUserReseller() && Boolean.TRUE.equals(product.getActive());
		model.addAttribute("addToCart", addToCart);
		model.addAttribute("PURPOSE_PERSONS", Product.PURPOSE_PERSONS);
		model.addAttribute("PURPOSE_COMPANIES", Product.PURPOSE_COMPANIES);

		Collection<ComboBoxSupport> purposeses = new ArrayList<ComboBoxSupport>();

		purposeses.add(new ComboBoxSupport(Product.PURPOSE_PERSONS, messageSource.getMessage("label.products.purpose."
				+ Product.PURPOSE_PERSONS, null, LocaleContextHolder.getLocale())));
		purposeses.add(new ComboBoxSupport(Product.PURPOSE_COMPANIES, messageSource.getMessage(
				"label.products.purpose." + Product.PURPOSE_COMPANIES, null, LocaleContextHolder.getLocale())));

		model.addAttribute("purposeses", purposeses);

		return "products/show";
	}

	@RequestMapping("/offers/{purpose}")
	public String listProducts(@PathVariable("purpose") Integer purpose,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size, Model model) {

		List<Product> results = null;

		String labelKey = "label.products.purpose." + purpose;

		if (page != null || size != null) {
			int sizeNo = size == null ? OptitronicsConstants.PAGE_SIZE : size.intValue();
			results = Product.findProducts(purpose, page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo);

			float nrOfPages = (float) Product.countProducts(purpose) / sizeNo;
			model.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
					: nrOfPages));
		} else {
			results = Product.findProducts(purpose, -1, -1);
		}

		model.addAttribute("labelKey", labelKey);
		model.addAttribute("products", results);
		model.addAttribute("purpose", purpose);
		model.addAttribute("PURPOSE_COMPANIES", Product.PURPOSE_COMPANIES);
		model.addAttribute("PURPOSE_PERSONS", Product.PURPOSE_PERSONS);
		model.addAttribute("addToCart", OptitronicsUtils.isUserReseller());
		model.addAttribute("update", OptitronicsUtils.isUserAdmin());
		model.addAttribute("size", OptitronicsConstants.PAGE_SIZE);

		return "products/list";
	}

	Converter<Product, String> getProductConverter() {
		return new Converter<Product, String>() {
			public String convert(Product product) {
				return new StringBuilder().append(product.getVersion()).append(" ").append(product.getName())
						.append(" ").append(product.getTaxIncludedInPrice()).toString();
			}
		};
	}

	@PostConstruct
	void registerConverters() {
		conversionService.addConverter(getProductConverter());
	}

}
